using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Macaw.Moss2007.XmlSitemapSolution
{
    class XmlSitemapJobFeatureReceiver : SPFeatureReceiver
    {
        private void ApplyWebConfigModificationsToFarm(SPWebApplication webApp)
        {
            try
            {
                webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }
            catch (System.UnauthorizedAccessException ex)
            {
                /*SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    EventLog.WriteEntry(this.GetType().FullName, string.Format("Exception occured running the FeatureReceiver when ApplyWebConfigModifications was called.{0}If you give WSS_WPG user account full permission to the config folder the error will disappear!{0}{1}", Environment.NewLine, ex.ToString()), EventLogEntryType.Error);
                });*/
                throw;
            }
        }

        private string Owner
        {
            get
            {
                return this.GetType().FullName ;
            }
        }

        private const string SITEMAPXML = "sitemap.*.xml";
        private SPWebConfigModification AddHttpHandler_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification(string.Format("add[@path='{0}']", SITEMAPXML), "configuration/system.web/httpHandlers");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                modification.Value = string.Format("<add verb=\"GET\" path=\"{0}\" type=\"{1}, {2}\"  />", SITEMAPXML, typeof(XmlSitemapHandler).FullName , typeof(XmlSitemapHandler).Assembly.FullName );
                modification.Owner = Owner;
                return modification;
            }
        }

        private const string SITEMAPINDEXXML = "sitemap.xml";
        private SPWebConfigModification AddHttpHandlerIndex_modification
        {
            get
            {
                SPWebConfigModification modification = new SPWebConfigModification(string.Format("add[@path='{0}']", SITEMAPINDEXXML), "configuration/system.web/httpHandlers");
                modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                modification.Value = string.Format("<add verb=\"GET\" path=\"{0}\" type=\"{1}, {2}\"  />", SITEMAPINDEXXML, typeof(XmlSitemapIndexHandler).FullName, typeof(XmlSitemapIndexHandler).Assembly.FullName);
                modification.Owner = Owner;
                return modification;
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;

            #region Make web.config modifications
            webapp.WebConfigModifications.Add(AddHttpHandler_modification);
            webapp.WebConfigModifications.Add(AddHttpHandlerIndex_modification);

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            ApplyWebConfigModificationsToFarm(webapp);
            #endregion


            XmlSitemapJobDefinition job = (XmlSitemapJobDefinition)webapp.JobDefinitions[XmlSitemapJobDefinition.JobId];
            if (job != null)
            {
                job.Delete();
            }

            job = new XmlSitemapJobDefinition(XmlSitemapJobDefinition.JobName, webapp);
            job.Update();
            
            //job.Execute(Guid.Empty);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;

            #region Undo web.config modifications
            for (int idx = webapp.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                try
                {
                    SPWebConfigModification conmod = webapp.WebConfigModifications[idx];
                    if (string.Compare(conmod.Owner, Owner, true) == 0)
                    {
                        webapp.WebConfigModifications.RemoveAt(idx);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            webapp.Update(); // Important
            ApplyWebConfigModificationsToFarm(webapp);
            #endregion

            XmlSitemapStorageCollection storagecollection = new XmlSitemapStorageCollection(webapp);
            foreach (XmlSitemapStorage sitemapstorage in storagecollection)
            {
                sitemapstorage.Delete();
            }

            XmlSitemapJobDefinition job = (XmlSitemapJobDefinition)webapp.JobDefinitions[XmlSitemapJobDefinition.JobId];
            if (job != null)
            {
                job.Delete();
                webapp.Update();
            }
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {

        }
    }
}
